﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Microsoft.Win32Ex.Tests
{
    [TestClass]
    public class ExtensionMethodTests
    {
        [TestMethod]
        public void IntPtrTest_AsEnumerable()
        {
            var expected = new List<TestStruct>
            {
                new TestStruct
                {
                     Test1 = 1,
                     Test2 = 2,
                },
                new TestStruct
                {
                     Test1 = 3,
                     Test2 = 4,
                },
                new TestStruct
                {
                     Test1 = 5,
                     Test2 = 6,
                },
            };

            var ptr = expected.ToIntPtr();

            try
            {
                var actual = ptr.AsEnumerable<TestStruct>(expected.Count).ToList();

                CollectionAssert.AreEqual(expected, actual);
            }
            finally 
            {
                Marshal.FreeHGlobal(ptr);
            }
        }

        [TestMethod]
        public void CollectionToIntPtrTest()
        {
            var expected = new List<TestStruct>
            {
                new TestStruct
                {
                     Test1 = 1,
                     Test2 = 2,
                },
                new TestStruct
                {
                     Test1 = 3,
                     Test2 = 4,
                },
                new TestStruct
                {
                     Test1 = 5,
                     Test2 = 6,
                },
            };

            var ptr = expected.ToIntPtr();

            try
            {
                Assert.AreNotEqual(IntPtr.Zero, ptr);
            }
            finally
            {
                Marshal.FreeHGlobal(ptr);
            }
        }

        [TestMethod]
        public void IntPtrToStringTest()
        {
            const string str = "This is a test";

            var ptr = Marshal.StringToHGlobalAuto(str);
            try
            {
                var actual = ptr.ToStringAuto();

                Assert.AreEqual(str, actual);
            }
            finally
            {
                Marshal.FreeHGlobal(ptr);
            }
        }

        struct TestStruct
        {
            public int Test1;

            public int Test2;
        }
    }
}
